package org.hxzon.configdesigner.web.pages;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.hxzon.configdesigner.core.CfgInfo;
import org.hxzon.configdesigner.core.CfgParser;
import org.hxzon.configdesigner.core.CfgValue;
import org.hxzon.configdesigner.web.pages.base.PageBase;
import org.hxzon.configdesigner.web.util.CfgUtil;

public class CopyElement extends PageBase {

    @Property
    private CfgValue origCfg;
    @Property
    private String childKey;
    //
    @InjectPage
    private View pageView;

    @OnEvent(EventConstants.ACTIVATE)
    Object init(int indexCode) {
        origCfg = CfgUtil.findCfg(indexCode);
        //
        if (origCfg.getParent().getCfgInfo().getType() == CfgInfo.Type_List) {
            CfgValue copyCfg = CfgParser.copy(origCfg);
            origCfg.getParent().addValue(copyCfg);
            CfgUtil.indexCfg(copyCfg);
            return pageView.withInit(copyCfg.indexCode());
        }
        return null;
    }

    @OnEvent(EventConstants.SUBMIT)
    Object submit() {
        CfgValue copyCfg = CfgParser.copy(origCfg);
        origCfg.getParent().addValue(childKey, copyCfg);
        CfgUtil.indexCfg(copyCfg);
        return pageView.withInit(copyCfg.indexCode());
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object toPassivate() {
        return origCfg.indexCode();
    }
}
